package msa.ch03.displayable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;

import msa.ch03.MessageReceiverMidlet;
import msa.ch03.data.StoredMessage;
import msa.util.View;

public class FormMessageDetails extends Form {

	private final View view;
	
	private final Command backCommand;
	
	private final StringItem subject;
	
	private final StringItem addressTo;
	private final StringItem addressCc;
	private final StringItem addressBcc;
	private final StringItem addressFrom;
	
	private class MessageDetailsCommandListener implements CommandListener {

		public void commandAction(Command c, Displayable d) {
			if (c == backCommand) {
				view.show(MessageReceiverMidlet.COMMAND_LIST);
			} else {
				throw new RuntimeException("UNKNOWN COMMAND:" + c);
			}
		}
		
	}
	
	public FormMessageDetails(View view) {
		super("Message details");
		this.view = view;
		
		backCommand = new Command("Back", Command.BACK, 1);
		
		subject = new StringItem("Subject: ", "");

		addressFrom = new StringItem("From:", "");
		addressTo = new StringItem("To: ", "");
		addressCc = new StringItem("Cc:", "");
		addressBcc = new StringItem("Bcc:", "");
		
		append(subject);
		append(addressFrom);
		append(addressTo);
		append(addressCc);
		append(addressBcc);
		
		addCommand(backCommand);
		setCommandListener(new MessageDetailsCommandListener());
	}

	
	public void loadMessage(StoredMessage message) {
		subject.setText(message.getSubject());
		
		addressFrom.setText(convertToString(message.getAdressesFrom()));
		addressTo.setText(convertToString(message.getAdressesTo()));
		addressCc.setText(convertToString(message.getAdressesCc()));
		addressBcc.setText(convertToString(message.getAdressesBcc()));
	}


	private String convertToString(String[] stringArray) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < stringArray.length; i++) {
			buffer.append(stringArray[i]);
			if ((i+1) < stringArray.length) {
				buffer.append(", ");	
			}
		}
		return buffer.toString();
	}
	
}
